package os.kai.aiu;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SplitNovelChapter {
    private static void split(List<String> inputs, String inputEncoding, String outputPrefix, String outputSuffix, String outputEncoding, String chapterPrefix, String chapterSuffix) throws IOException {
        int preLen = chapterPrefix.length();
        try(IncreaseWriter writer = new IncreaseWriter(outputPrefix,outputSuffix,outputEncoding,0)){
            for(String input : inputs){
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(input)),inputEncoding))){
                    String line;
                    while((line=reader.readLine())!=null){
                        String trimmed = line.trim();
                        int len = trimmed.length();
                        if(len>preLen&&trimmed.startsWith(chapterPrefix)){
                            int si = trimmed.indexOf(chapterSuffix,preLen);
                            if(si>0){
                                //is chapter start
                                int cc = MathUtil.parseChineseNumberUnder9999(trimmed.substring(preLen,si));
                                if(cc>0){
                                    writer.flush();
                                    writer.setIndex(cc);
                                }
                            }
                        }
                        writer.println(line);
                    }
                }
            }
        }
    }

    public static void splitXCZZ() throws IOException {
        List<String> inputs = Arrays.asList(
                "D:\\work\\aigc\\novels\\星辰之主\\星辰之主(1-500章).txt",
                "D:\\work\\aigc\\novels\\星辰之主\\星辰之主(501-1000章).txt",
                "D:\\work\\aigc\\novels\\星辰之主\\星辰之主(1001-1500章).txt",
                "D:\\work\\aigc\\novels\\星辰之主\\星辰之主(1501-2000章).txt",
                "D:\\work\\aigc\\novels\\星辰之主\\星辰之主(2001-2031章).txt"
        );
        String outputPrefix = "D:\\work\\aigc\\novels\\星辰之主\\split\\xczz_";
        String outputSuffix = ".txt";
        split(inputs,"UTF-8",outputPrefix,outputSuffix,"UTF-8","第","章");
    }

    public static void splitBaNan() throws IOException {
        List<String> inputs = Collections.singletonList(
                "D:\\work\\aigc\\novels\\八男\\八男1-163简体.txt"
        );
        String outputPrefix = "D:\\work\\aigc\\novels\\八男\\split\\banan_";
        String outputSuffix = ".txt";
        split(inputs,"UTF-8",outputPrefix,outputSuffix,"UTF-8","第","话");
    }

    public static void main(String[] args) throws IOException {
        splitBaNan();
    }
}
